import { notNilEmpty } from 'qx-util';
import { ConfigService } from '../../service';
import { ThemeUtil } from './theme-util';

export interface ICustomThemeState {
  /**
   * 主题标识
   *
   * @type {string}
   * @memberof ICustomThemeState
   */
  themeTag: string;

  /**
   * 主题变量
   *
   * @type {Record<string, string>}
   * @memberof ICustomThemeState
   */
  themeVars: Record<string, string>;
}

/**
 * 自定义主题工具类
 *
 * @author zzq
 * @date 2024-05-10 23:12:15
 * @export
 * @class CustomThemeUtil
 */
export class CustomThemeUtil {
  /**
   * 应用配置存储服务
   *
   * @type {(ConfigService | undefined)}
   * @memberof CustomThemeUtil
   */
  config: ConfigService | undefined;

  /**
   * 自定义主题状态
   *
   * @type {ICustomThemeState}
   * @memberof CustomThemeUtil
   */
  public state: ICustomThemeState = {} as ICustomThemeState;

  constructor(protected themeUtil: ThemeUtil) {
    this.state.themeTag = ibiz.util.theme.getTheme();
    this.state.themeVars = {};
    const { appData } = ibiz;
    if (!appData) {
      return;
    }
    const app = ibiz.hub.getApp();
    this.config = new ConfigService(
      app.appId,
      'customtheme',
      `theme_config_${appData.context.srfuserid}`,
    );
  }

  /**
   * 转换自定义变量
   *
   * @param {Record<string, string>} themeVars
   * @return {string}
   * @memberof CustomThemeUtil
   */
  transCustomVars(themeVars: Record<string, string>): string {
    let result = '';
    for (const key in themeVars) {
      if (Object.prototype.hasOwnProperty.call(themeVars, key)) {
        const val = themeVars[key];
        result += `.${key}{${val}}`;
      }
    }
    return result;
  }

  /**
   * 设置自定义主题测试
   *
   * @param {string} themeTag
   * @param {Record<string, string>} themeVars
   * @memberof CustomThemeUtil
   */
  setCustomThemeParams(
    themeTag: string,
    themeVars: Record<string, string>,
  ): void {
    // const themeStyle = document.getElementById(themeTag);
    // if (themeStyle) {
    //   themeStyle.remove();
    // }
    // const otherContent: IData = {};
    // let content = `:root.${themeTag}{`;
    // for (const key in themeVars) {
    //   if (Object.prototype.hasOwnProperty.call(themeVars, key)) {
    //     if (key.split(':').length === 2) {
    //       const className = key.split(':')[0];
    //       const varName = key.split(':')[1];
    //       const val = themeVars[key];
    //       if (!otherContent[className]) {
    //         otherContent[className] = '';
    //       }
    //       otherContent[className] +=
    //         `${varName}: ${val}${val.endsWith(';') ? '' : ';'}`;
    //     } else {
    //       const val = themeVars[key];
    //       content += `${key}: ${val}${val.endsWith(';') ? '' : ';'}`;
    //     }
    //   }
    // }
    // content += '}';
    // content += this.transCustomVars(otherContent);
    // const script = document.createElement('style');
    // script.id = themeTag;
    // script.type = 'text/css';
    // script.innerHTML = content;
    // document.head.appendChild(script);
  }

  /**
   * 清除自定义主题参数
   *
   * @memberof CustomThemeUtil
   */
  clearCustomThemeParams(): void {
    // this.state.themeVars = {};
    // const themeStyle = document.getElementById(this.state.themeTag);
    // if (themeStyle) {
    //   themeStyle.remove();
    // }
  }

  /**
   * 加载自定义主题
   *
   * @return {*}  {Promise<IData>}
   * @memberof CustomThemeUtil
   */
  async loadCustomTheme(): Promise<IData> {
    const res = await this.config!.load();
    if (notNilEmpty(res.themeVars)) {
      if (res.themeTag) {
        this.state.themeTag = res.themeTag;
        ibiz.util.theme.setTheme(this.state.themeTag);
      }
      this.state.themeVars = res.themeVars;
      this.setCustomThemeParams(this.state.themeTag, res.themeVars);
    }
    return res;
  }

  /**
   * 预览自定义主题
   *
   * @param {string} themeTag
   * @param {Record<string, string>} themeVars
   * @return {*}  {ICustomThemeState}
   * @memberof CustomThemeUtil
   */
  previewCustomTheme(
    themeTag: string,
    themeVars: Record<string, string>,
  ): ICustomThemeState {
    if (themeTag) {
      this.state.themeTag = themeTag;
      ibiz.util.theme.setTheme(this.state.themeTag);
    }
    if (notNilEmpty(themeVars)) {
      this.state.themeVars = themeVars;
      this.setCustomThemeParams(this.state.themeTag, themeVars);
    }
    return this.state;
  }

  /**
   * 保存自定义主题
   *
   * @param {string} themeTag
   * @param {Record<string, string>} themeVars
   * @return {*}  {Promise<boolean>}
   * @memberof CustomThemeUtil
   */
  async saveCustomTheme(
    themeTag: string,
    themeVars: Record<string, string>,
  ): Promise<boolean> {
    const data = {
      themeTag,
      themeVars,
    };
    const result = await this.config!.save(data);
    if (result) {
      ibiz.message.success('保存自定义主题成功!');
    }
    return result;
  }

  /**
   * 分享自定义主题
   *
   * @param {string} themeTag
   * @param {Record<string, string>} themeVars
   * @return {*}  {(Promise<string | undefined>)}
   * @memberof CustomThemeUtil
   */
  async shareCustomTheme(
    themeTag: string,
    themeVars: Record<string, string>,
  ): Promise<string | undefined> {
    const { appData } = ibiz;
    if (!appData) {
      return;
    }
    const data = {
      themeTag,
      themeVars,
    };
    const app = ibiz.hub.getApp();
    const timestamp = Date.now();
    const shareConfig = new ConfigService(
      app.appId,
      'customtheme',
      `theme_share_${appData.context.srfuserid}_${timestamp}`,
    );
    const result = await shareConfig.save(data);
    if (result) {
      // const { origin, pathname } = window.location;
      // const shareThemeId = `shareThemeId=${window.btoa(timestamp.toString())}`;
      // const shareUserName = `shareUserName=${encodeURIComponent(appData.context.srfusername)}`;
      // const shareUserId = `shareUserId=${encodeURIComponent(appData.context.srfuserid)}`;
      // const url = `/share?${shareThemeId}&${shareUserName}&${shareUserId}`;
      return ``;
    }
    ibiz.message.error('分享自定义主题失败!');
  }

  /**
   * 获取分享主题
   *
   * @param {string} userId
   * @param {string} themeId
   * @return {*}  {Promise<IData>}
   * @memberof CustomThemeUtil
   */
  async getShareTheme(userId: string, themeId: string): Promise<IData> {
    const app = ibiz.hub.getApp();
    const shareConfig = new ConfigService(
      app.appId,
      'customtheme',
      `theme_share_${userId}_${themeId}`,
    );
    return shareConfig.load();
  }
}
